package com.bob.web.dao;

import com.bob.web.common.constant.Page;
import com.bob.web.entity.system.Role;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

/**
 * 名称: RoleDao<br>
 * 描述:<br>
 * 类型: JAVA<br>
 * 最近修改时间:2017/7/20 14:21<br>
 *
 * @author BoYangsh
 * @version [版本号, V1.0]
 * @since 2017/7/20 14:21
 */
//@Repository
public class RoleDao extends BaseMongoDaoSupport {

	public List<Role> findRole(List<String> names, String...fields) {
		Query query = Query.query(Criteria.where("name").in(names));
		includes(query, fields);
		return find(query, Role.class);
	}

	/**
	 * 查找角色的分页数据
	 * @param page
     */
	public void findPage(Page<Role> page) {
		Query query = new Query();
		findPage(query, page, Role.class);
	}

	/**
	 * 添加角色
	 * @param role
     */
	public void addRole(Role role) {
		insert(role);
	}

	/**
	 * 根据id号查找角色
	 * @param id
	 * @return
     */
	public Role findRoleById(Long id, String...fields) {
		Query query = Query.query(Criteria.where("_id").is(id));
		includes(query, fields);
		return findOne(query, Role.class);
	}

	/**
	 * 根据角色id查找角色
	 * @param ids
	 * @param fields
     * @return
     */
	public List<Role> findRolesByIds(List<Long> ids, String...fields) {
		Query query = Query.query(Criteria.where("_id").in(ids));
		includes(query, fields);
		return find(query, Role.class);
	}

	/**
	 * 按照id查找和修改角色
	 * @param roleId
	 * @param resourceIds
	 */
	public void findAndModifyById(Long roleId, Set<Long> resourceIds) {
		Query query = Query.query(Criteria.where("_id").is(roleId));
		Update update = Update.update("resources", resourceIds);
		findAndModify(query, update, Role.class);
	}

	/**
	 * 查找所有的角色
	 * @return
	 */
	public List<Role> findAllRoles() {
		Query query = new Query();
		query.with(new Sort(Sort.Direction.DESC, "_id"));
		return find(query, Role.class);
	}
}
